const app = getApp();
const ipUrl = app.globalData.ipUrl;
const HttpUtil = require('../utils/httpUtil')
// 下载临时文件
function downloadTempFile(fileUrl) {
    return new Promise((resolve, reject) => {
        if (fileUrl.startsWith("wxfile://")) {
            console.log("wxfile!!!")
            resolve(fileUrl);
        }else{
            wx.downloadFile({
                url: fileUrl,
                success(res) {
                    if (res.statusCode === 200) {
                        console.log('下载成功')
                        resolve(res.tempFilePath);
                    } else {
                        reject('下载文件失败');
                    }
                },
                fail(err) {
                    reject(err);
                }
            });
        }
    });
}

// 上传文件
function uploadFile(filePath, params) {
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: ipUrl + '/update_user_info/',
            filePath: filePath,
            name: 'avatar',
            formData: {
                username: params.username,
                profile: params.profile,
                nickname: params.nickname,
                email: params.email,
                phone: params.phone,
                gender: params.gender,
                birthday: params.birthday,
            },
            header: {
                'content-type': 'multipart/form-data'
            },
            success(res) {
                if (res.statusCode === 200) {
                    resolve(JSON.parse(res.data));
                } else {
                    console.log("失败"+res.data)
                    reject(JSON.parse(res.data));
                }
            },
            fail(err) {
                reject(err);
            }
        });
    });
}

// 更新用户信息
export async function updateUserinfo(params) {
    try {
        // 下载临时文件
        const filePath = await downloadTempFile(params.avatar);
        // 上传文件并更新用户信息
        const response = await uploadFile(filePath, params);
        console.log('更新用户信息成功', response);
        return response;
    } catch (error) {
        console.error('更新用户信息失败', error);
        throw error;
    }
}